<template>
    <div class="maps-wrapper">
        <div v-if="showMenu" id="up-map-div">
            <button class="close-button" @click="closeMenuInfo">关闭</button>
            <header-tab-bar/>
            <header-table-view :data-source="videoDataList" :selected-id="selectId" @select-action="clickInfoAction"/>
            <console-header-view/>
            <status-tab-view @online-status-switch="onlineStatusChange"/>
            <cloud-control-view-header/>
            <cloud-control-item-view @button-move="controlAction"/>
            <camera-control-header-view/>
            <camera-control-shoot-view :is-show-take-photo="isShowTakePhoto" @shoot-action="showMapPoint"
                                       @stop-action="endVideoRecord"/>
            <camera-control-tab-view :selected-type="cameraModeStr" @select-action="cameraModeChange"/>
        </div>
        <div v-else class="close-map-div">
            <el-button type="primary" @click="showMenuInfo">展开</el-button>
        </div>
        <Map ref="mapView"/>
        <Video v-show="isShowVideoMenu" :data-source="data" video-url=""/>
    </div>
</template>

<script>
	import Map from '@/components/maps/Map'
	import HeaderTabBar from '@/components/maps/header-tab-bar'
	import HeaderTableView from '@/components/maps/header-table-view'
	import ConsoleHeaderView from '@/components/maps/console-header-view'
	import StatusTabView from '@/components/maps/status-tab-view'
	import CloudControlViewHeader from '@/components/maps/cloud-control-view-header'
	import CloudControlItemView from '@/components/maps/cloud-control-item-view'
	import CameraControlHeaderView from '@/components/maps/camera-control-header-view'
	import CameraControlShootView from '@/components/maps/camera-control-shoot-view'
	import CameraControlTabView from '@/components/maps/camera-control-tab-view'
	import {getVideoPlayerList} from '../request/api'
	import Video from "../components/maps/Video"
	// import store from '@/store'

	const CAMERA_MODE = 2001
	const RECORD_MODE = 2002
	const TAKE_PHOTO = 2003
	const START_RECORD = 2004
	const STOP_RECORD = 2005

	const YUN_TAI_UP = 3001
	const YUN_TAI_DOWN = 3002
	const YUN_TAI_LEFT = 3003
	const YUN_TAI_RIGHT = 3004
	const YUN_TAI_CENTER = 3005
	const VIDEO_INFO_ON = 0
	const VIDEO_INFO_OFF = 1

	export default {
		name: 'Maps',
		components: {
			Video,
			Map,
			HeaderTabBar,
			HeaderTableView,
			ConsoleHeaderView,
			StatusTabView,
			CloudControlViewHeader,
			CloudControlItemView,
			CameraControlHeaderView,
			CameraControlShootView,
			CameraControlTabView
		},
		data() {
			return {
				websocket: undefined,
				locationPos: [],
				showMenu: false, // 是否展开菜单
				isShowVideoMenu: false,
				videoDataList: [],
				selectId: '', // 默认触发的id
				videoUrl: '',
				cameraMode: CAMERA_MODE,
				cameraModeStr: '拍照',
				isShowTakePhoto: true, // 是否显示拍照按钮, 点击录制时候就会隐藏
				selectObject: {
					droneName: '暂无',
					userName: '暂无',
					remainPercent: 0,
					height: 0,
					speed: 0,
					locatePos: null
				},
				data: {
					username: 'xxx',// 飞手名称
					team: 'xxx',// 团队
					droneName: 'xxx',// 设备名称
					remainPercent: '66',// 电池电量
					height: '66',//高度
					speed: '66',// 速度
					state: '飞不动',// 飞行状态
					signalState: '杠杆的'// 信号状态
				}
			}
		},
		created() {
			// 链接websocket获取后台给的gps数组
			this.initWebSocket()
			this.getVideoList()
		},
		methods: {
			async initWebSocket() {
				// const res = await store.dispatch('GetInfo')
				// const username = res.user.username
				const username = 'xxx'
				const wsUri = process.env.VUE_APP_WS_API + `/webSocket/${username}`
				this.websock = new WebSocket(wsUri)
				this.websock.onerror = this.webSocketOnError
				this.websock.onmessage = this.webSocketOnMessage
			},
			webSocketOnError() {
				this.$notify({
					title: 'WebSocket连接发生错误',
					type: 'error',
					duration: 0
				})
			},
			webSocketOnMessage(e) {
				const data = JSON.parse(e.data) // 如果是3就是导航GPS定位
				const msgTypeCode = data.msgType.code
				if (msgTypeCode === 3) {
					// 获取坐标轴进行定位获取
					if (this.selectId.toString() === data.data.id.toString()) {
						const locationPos = data.data.locateData
						const longitude = locationPos.longitude
						const latitude = locationPos.latitude
						this.locationPos.push([longitude, latitude])
					}
				} else if (msgTypeCode === 2) {
					// 判断是不是当前的飞行器
					// console.log(this.selectId)
					if (this.videoDataList.length === 0) {
						this.getVideoList() // 获取当前的列表
					}
					if (this.selectId.toString() === data.data.id.toString()) {
						this.selectObject = {
							droneName: this.selectObject.droneName,
							userName: this.selectObject.userName,
							remainPercent: data.data.batteryData.remainPercent,
							height: data.data.attitudeData.vps,
							speed: data.data.attitudeData.horizontalSpeed.toFixed(2),
							locatePos: [data.data.userLocateData.longitude, data.data.userLocateData.latitude]
						}
					}
				} else if (msgTypeCode === YUN_TAI_UP) {
					console.log('抬起来')
				} else if (msgTypeCode === YUN_TAI_DOWN) {
					console.log('放下去')
				} else if (msgTypeCode === YUN_TAI_LEFT) {
					console.log('左侧')
				} else if (msgTypeCode === YUN_TAI_RIGHT) {
					console.log('右侧')
				} else if (msgTypeCode === YUN_TAI_CENTER) {
					console.log('中间回调')
				} else if (msgTypeCode === CAMERA_MODE) {
					console.log('相机')
				} else if (msgTypeCode === RECORD_MODE) {
					console.log('拍照')
				} else if (msgTypeCode === TAKE_PHOTO) {
					console.log('TAKE_PHOTO')
				} else if (msgTypeCode === START_RECORD) {
					console.log('开始录制')
				} else if (msgTypeCode === STOP_RECORD) {
					console.log('停止录制')
				} else if (msgTypeCode === VIDEO_INFO_ON) {
					// 视频开始的回调
					if (this.selectId.toString() === data.data.id.toString()) {
						this.videoUrl = data.data.pullUrl
					}
				} else if (msgTypeCode === VIDEO_INFO_OFF) {
					// 视频开始的回调
					if (this.selectId.toString() === data.data.id.toString()) {
						this.videoUrl = ''
					}
				}
			},
			// 点击地图标注,参数为e
			showMapPoint() {
				// console.log('触发')
				// this.$refs['mapView'].showPoint()
				if (this.cameraMode === CAMERA_MODE) {
					this.isShowTakePhoto = true
					this.webSocketSend({
						data: undefined,
						type: TAKE_PHOTO
					})
				} else {
					this.isShowTakePhoto = false
					this.webSocketSend({
						data: undefined,
						type: START_RECORD
					})
				}
			},
			endVideoRecord() {
				this.isShowTakePhoto = true
				this.webSocketSend({
					data: undefined,
					type: STOP_RECORD
				})
			},
			// 点击展开
			showMenuInfo() {
				this.showMenu = true
			},
			closeMenuInfo() {
				this.showMenu = false
			},
			async getVideoList() {
				try {
					const res = await getVideoPlayerList()
					this.videoDataList = res
					this.selectId = this.videoDataList.length > 0 ? this.videoDataList[0].id : ''
					console.log(this.selectId)
					this.videoUrl = this.videoDataList.length > 0 ? this.videoDataList[0].pullUrl : ''
					// 如果在录制状态，默认进入摄像选择，进入录制阶段
					if (this.videoDataList.length > 0) {
						this.selectObject = {
							droneName: this.videoDataList[0].droneName,
							userName: this.videoDataList[0].userName,
							remainPercent: this.videoDataList[0].remainPercent,
							height: 0,
							speed: 0,
							locatePos: null
						}
					}
				} catch (e) {
					console.log(e)
				}
			},
			clickInfoAction(e) {
				this.selectId = e.id
				this.videoUrl = e.pullUrl
				this.locationPos = [] // 重新初始化坐标轴
				this.selectObject = {
					droneName: e.droneName,
					userName: e.userName,
					remainPercent: e.remainPercent,
					height: 0,
					speed: 0,
					locatePos: null
				}
			},
			webSocketSend({data, type}) {
				// 没有选择默认返回不发送
				if (this.selectId === '') {
					console.log('没有设备')
					return
				}
				this.websock.send(JSON.stringify({
					data,
					type,
					id: this.selectId
				}))
			},
			controlAction(type) {
				switch (type) {
					case 'top-id':
						this.webSocketSend({
							data: undefined,
							type: YUN_TAI_UP
						})
						break
					case 'bottom-id':
						this.webSocketSend({
							data: undefined,
							type: YUN_TAI_DOWN
						})
						break
					case 'left-id':
						this.webSocketSend({
							data: undefined,
							type: YUN_TAI_LEFT
						})
						break
					case 'right-id':
						this.webSocketSend({
							data: undefined,
							type: YUN_TAI_RIGHT
						})
						break
					case 'middle-id':
						this.webSocketSend({
							data: undefined,
							type: YUN_TAI_CENTER
						})
						break
				}
				// const resultStr = JSON.stringify({
				//   msgType: 3,
				//   action: 'move'
				// })
				// this.webSocketSend(resultStr)
			},
			onlineStatusChange(status) {
				// 显示和关闭直播
				this.isShowVideoMenu = status
			},
			cameraModeChange(e) {
				// 如果没有停止录制切换就会停止录制
				if (!this.isShowTakePhoto) {
					this.webSocketSend({
						data: undefined,
						type: STOP_RECORD
					})
				}
				this.cameraMode = e === 1 ? CAMERA_MODE : RECORD_MODE
				this.webSocketSend({
					data: undefined,
					type: this.cameraMode
				})
			}
		}
	}
</script>

<style scoped lang="scss">
    .maps-wrapper {
        margin-left: 100px;
        height: 100%;
        position: relative;

        #up-map-div {
            margin: 0;
            position: absolute;
            left: 32px;
            top: 32px;
            bottom: 32px;
            max-height: calc(100% - 32px);
            overflow-y: auto;
            overflow-x: hidden;
            z-index: 1;
            background-color: rgba(67, 75, 98, 0.8);
            border-radius: 10px;
            box-shadow: 0 15px 70px 0 rgba(0, 0, 0, 0.05);

            &::-webkit-scrollbar {
                display: none;
            }

            .close-button {
                position: absolute;
                right: 0;
                top: 0;
                background-color: rgba(0, 0, 0, 0);
                border-width: 0;
                color: #FFFFFF;
                font-size: 14px;
                height: 40px;
                font-family: PingFang SC;
                font-weight: bold;
                padding: 15px;
                z-index: 1;
                cursor: pointer;
            }
        }

        .close-map-div {
            position: absolute;
            display: flex;
            justify-content: center;
            align-items: center;
            left: 32px;
            top: 32px;
            width: 100px;
            height: 64px;
            z-index: 1;
            background-color: rgba(67, 75, 98, 0.8);
            border-radius: 10px;
            box-shadow: 0px 15px 70px 0px rgba(0, 0, 0, 0.05);
            text-align: center;
        }

        .video-show {
            background-color: black;
            position: absolute;
            right: 20px;
            width: 545px;
            height: 445px;
            top: 105px;
            z-index: 900;
            border-radius: 10px;
        }
    }
</style>
